
package com.amigo.online.provider.video.service.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSONObject;
import com.amigo.online.common.param.result.UserInfo;
import com.amigo.online.common.param.result.promote.PromoteOrderDetailInfo;
import com.amigo.online.common.param.result.promote.PromoteOrderInfo;
import com.amigo.online.provider.video.common.GlobalController;
import com.amigo.online.provider.video.common.RwRedisService;
import com.amigo.online.provider.video.mapper.PromoteMapper;
import com.amigo.online.provider.video.mapper.PromoteOrderMapper;
import com.amigo.online.provider.video.mapper.UserBalanceMapper;
import com.amigo.online.provider.video.mapper.VideoRecommendMapper;
import com.amigo.online.provider.video.service.PromoteService;
import com.amigo.online.provider.video.util.TodayZeroPointTimeStampsUtil;

@Service
public class PromoteServiceImpl implements PromoteService {
    @Autowired
    PromoteMapper promoteMapper;
    @Autowired
    VideoRecommendMapper videoRecommendMapper;
    @Autowired
    PromoteOrderMapper promoteOrderMapper;
    @Autowired
    UserBalanceMapper userBalanceMapper;
    @Autowired
    RwRedisService rwRedisService;

    private final static int DEFAULT_VIEW_AMOUNT_FACTOR = 50;
    private final static String DAILY_COST_KEY_PREFIX = "m:dailycost:";

    @Override
    public Integer getExpectedViewAmount(Integer money, Integer type) {
        //50,40，系统投放的倍数是50，自定义是40，此数据从数据库中查
        //money的单位是分
        return money / 100 * (type == 1 ? 50 : type == 2 ? 40 : DEFAULT_VIEW_AMOUNT_FACTOR);
    }

    @Override
    @Transactional(readOnly = true)
    public JSONObject getMyPromoteInfo(Integer page, Integer size) {
        UserInfo user = GlobalController.getNowUser();
        Integer offset = (page - 1) * size;
        List<PromoteOrderInfo> promoteOrderInfoList = promoteMapper.getPromoteByUserId(user.getId(), size, offset);
        JSONObject result = new JSONObject();
        result.put("record", promoteOrderInfoList);
        Integer balance = userBalanceMapper.getBalanceByUserId(user.getId());
        result.put("account_balance", balance == null || balance < 0 ? 0 : balance);    //账户余额
        Integer expend_today = (Integer) rwRedisService.opsForHashRead().get(DAILY_COST_KEY_PREFIX + TodayZeroPointTimeStampsUtil.getTodayZeroPointTimeStamps(),
                user.getId());
        result.put("expend_today", expend_today == null || expend_today < 0 ? 0 : expend_today);    //今日消耗(未计算)
        return result;
    }


    @Override
    @Transactional(readOnly = true)
    public PromoteOrderDetailInfo getPromoteOrderDetail(Long promoteOrderId) {
        PromoteOrderDetailInfo res = promoteMapper.getPromoteOrderDetail(promoteOrderId);

//		res.setPlay_amount(999);//播放量提升
        return res;
    }
}
